import { EventBus } from "@/tools/bus";
import { wsSend } from "@/tools/sendMessage";
import { getOperateRecord, submitOperateRecord } from "@/api/api";

export const pageHandler={
  data() {
    return {
      operationRecordsDialogVisible : false,
      operationRecordsData : [],
      pageData:null,
      rightMenuObj: null,
      yaokongMsg: '',
      showMenu:false,
      canyaoKong:false,
      operatorPwdDialogVisible_0:false,
      operatorPwdDialogVisible:false,
      canSubmit: true,
      canHandle:this.$store.state.canHandle ,
      operatorPwdObj: {
        username: '',
        pwd: '',
      },
      adminPwdObj: {
        username: '',
        pwd: '',
      },
      userInfoJson:this.$store.state.handleUserInfo,
      currentSelectMenuItemObj:null,
      dialogVisible :false,
    }
  },
  methods: {
    messageHandler(data){
      const wsCmds = ['byqDwChange','switchIntervalClear','switchChange', 'monitorRemoteControl', 'switchClear', 'switchAllClear', 'monitorStateChange', 'addPromptLanguage', 'faultOccur'];
      if (data.cmd==='getJgFenTuPage'){
        this.pageData=JSON.parse(JSON.stringify(data.data))
        this.initData(this.pageData)
      }
      if (wsCmds.includes(data.cmd)) {
        this.dialogVisible = false;
        if (data.cmd !== 'monitorRemoteControl' && data.cmd !== 'monitorStateChange'&& data.cmd !== 'switchChange') {
          this.$message.success('操作成功');
        }
        if (data.cmd === 'monitorRemoteControl'){
          this.$message.success('操作成功');
          this.canHandle=false
        }
        if (data.cmd === 'switchChange'){
          this.canHandle=false
          if (+data.data.isLock===0){
            this.$message.success('操作成功');
          }else{
            this.$message.error('违反五防闭锁逻辑，操作失败');
            submitOperateRecord( {log_desc:`遥控${data.data.intervalName}间隔${data.data.switchNum}状态为${data.data.state === 0 ? '分位' : '合位'}时，违反五防闭锁逻辑！`},false)
          }

        }
        this.canSubmit = true;
        this.getPageData()
      }
    },
    cancelLeftClickMenu() {
      this.showMenu=false
    },
    routerToMainPage(){
      this.$router.push({ path: '/' })
    },
    goMap(){
      this.$router.push({
        path: '/map'
      })
    },
    clearAll(e){
      const params= {
        "cmd": "switchIntervalClear",
        "ftName":e
      }
      wsSend(params);
      submitOperateRecord({log_desc: params.ftName+'画面清闪'})
    },
    checkVal(val,page){
      let state_desc=page===true?val.page_position+'：'+val.state_desc:val.state_desc

      let num=val.state_val===''||val.state_val===undefined?'无':val.state_val
      let desc=this.$store.state.operDescData.find(item=>item.type==='jc'&&item.comType==='遥测').desc.replace('jgName',val.jg_name)
          .replace('devName',state_desc)
          .replace('state',num);
      val?.unit!==''||val?.unit!==undefined?desc+=val?.unit:''
      if (num==='无'){
        desc=this.$store.state.operDescData.find(item=>item.type==='jc'&&item.comType==='遥测').desc.replace('jgName',val.jg_name)
            .replace('devName',state_desc)
            .replace('数值为state','无数值');
      }
      submitOperateRecord({log_desc: desc})
    },
    itemRightClick(item, type, deviceName, state,data_id,jianGeMing,info) {
      this.yaokongMsg='正在进行遥控选择，请稍候...';
      this.canyaoKong=false
      let parmas = item
      if(type=='ruanyaban'){
        const {clientX, clientY} = item
        parmas = {
          clientX,
          clientY,
          info,
          jianGeMing,
          deviceName,
          type,
          data_id,
          currentObj: {
            name,
            state,
            controlStatusList: (type == 'yaoceliang')?[{value:0,label: '正常'},{value:1, label: '异常'}]:[{value:0,label: '退出'},{value:1, label: '投入'}],
          },
          yaokongObj: {
            value: 1,
            title: '110kV荷园变',
            measurePoint: deviceName ,
            state: state,
          },
        }
      }
      this.showMenu=true
      this.rightMenuObj = parmas
    },
    menuItemClick(item) {
      if (item.label==="遥控"){
        this.operatorPwdDialogVisible_0=true
      }
    },
    operationRecords() {
      this.operationRecordsDialogVisible = true
      this.operationRecordsData = [];
      this.getOperateRecordList();
      this.$nextTick(() => {
        this.$refs.operateRecordDialogRef.$el.style.pointerEvents = 'none';
      });
    },
    getOperateRecordList() {
      getOperateRecord({}).then(res => {
        if (res.data){
          const data = JSON.parse(JSON.stringify(res.data.map(o => {
            o.isHighlight = false;
            return o;
          })));
          if (this.operationRecordsData.length && this.operationRecordsData.length !== data?.length) {
            data[0].isHighlight = true;
          }
          this.operationRecordsData = data;
        }

      });
    },
    handleDialogClose(){
      this.$store.commit('canHandle',false)
      this.dialogVisible = false;
      this.canSubmit=true
      done();
    },
    async   handleBrand(){
      let currenInfo=[];
      let brandInfo=this.$store.state.brandInfo.split(';')
      let brandInfoCopy=this.$store.state.brandInfoCopy.split(';')
      if (this.$store.state.handleBrand==='guapai'){
        currenInfo = brandInfo.filter(item =>
            !brandInfoCopy.some(copy => copy === item)
        );

      }else{
        currenInfo = brandInfoCopy.filter(item =>
            !brandInfo.some(copy => copy === item)
        );
      }
      if (currenInfo.length===0){
        this.$message.error('牌信息无变化，请检查操作')
        return
      }
      const params={
        "cmd":'addPromptLanguage',
        "type":this.$store.state.handleBrand,
        "stateDesc":this.currentSelectMenuItemObj.stateDesc,
        "contents":currenInfo.join(';')+';'
      }
      this.websocketsend(params);
      this.getPageData();
      let log = {
        log_desc:params.stateDesc+"在"+ this.currentSelectMenuItemObj.jianGeMing+"间隔进行"+(params.type==="guapai"?"挂牌":"摘牌") + "操作,"+ (params.type==="guapai"?"挂牌":"摘牌")+"信息为:"+currenInfo.join(';')
      }
      let res = await submitOperateRecord(log)

    },
    yaokongSelect(){
      if (this.$store.state.canHandle){
        this.yaokongMsg='是否执行操作？';
        this.canyaoKong=true
      }else{
        this.yaokongMsg='遥控失败：遥控调度编号不匹配';
      }
    },
    getDesc(type,comType){
      return this.$store.state.operDescData.find(item=>item.type===type&&item.comType===comType).desc;
    },
    async	remoteControlSelect() {
      if (this.canSubmit){
        this.canSubmit=false
        if (this.currentSelectMenuItemObj.currentObj){
          if (this.currentSelectMenuItemObj.type==='ruanyaban'){
            this.sendMsgData={
              "cmd":'monitorRemoteControl',
              "intervalName": this.currentSelectMenuItemObj.info.jg_name,
              "switchNum": this.currentSelectMenuItemObj.info.state_desc,
              "state":this.$store.state.yaokongstate,
              "id":this.currentSelectMenuItemObj.info.id
            }
          }else {
            this.sendMsgData={
              "cmd":'switchChange',
              "data":{
                "intervalName": this.currentSelectMenuItemObj.info.jg_name,
                "switchNum": this.currentSelectMenuItemObj.info.state_desc,
                "state":this.$store.state.yaokongstate,
              }
            }
          }

        }
        const list_1=['gelidao','didao','duanluqi']
        const  map={
          'gelidao':'隔离刀',
          'didao':'地刀',
          'duanluqi':'断路器'
        }
        if (list_1.includes(this.currentSelectMenuItemObj.type)){
          this.desc=this.getDesc('cz','开关')
          this.desc=this.desc.replace('jgName',this.currentSelectMenuItemObj.info.jg_name).replace('devName',this.currentSelectMenuItemObj.deviceName+map[this.currentSelectMenuItemObj.type]).replace('state', (Number(this.$store.state.yaokongstate) === 0 ? "分" : "合"))
        }else{
          this.desc=this.getDesc('cz','压板')
          this.desc=this.desc.replace('jgName',this.currentSelectMenuItemObj.jg_name).replace('devName',this.currentSelectMenuItemObj.info.page_position+'：'+this.currentSelectMenuItemObj.deviceName+'软压板').replace('state', (Number(this.$store.state.yaokongstate) === 0 ? "退出" : "投入"))
        }
        let params = {
          log_desc:this.desc
        }
        // let params_2 = {
        //   log_desc: this.currentSelectMenuItemObj.deviceName+'在' +this.currentSelectMenuItemObj.jianGeMing+'间隔检查状态为' +
        //     (Number(this.$store.state.yaokongstate) === 0 ? "分位" : "合位"),
        // }
        // if (this.$store.state.setTicketType==='图形开票'){
        //   this.$store.commit('ticketHandleContent', {
        //     recordDesc:params.log_desc,
        //     operatePointName:this.currentSelectMenuItemObj.info.operate_point_name,
        //     operateState:this.$store.state.yaokongstate,
        //     operateType:"状态切换"
        //   })
        //   this.$nextTick(() => {
        //     this.$store.commit('ticketHandleContent', {
        //       recordDesc: params_2.log_desc,
        //       operatePointName: this.currentSelectMenuItemObj.info.operate_point_name || '',
        //       operateState: this.$store.state.yaokongstate,
        //       operateType: "状态检查"
        //     });
        //   });
        // }else{
        //   this.$store.commit('ticketHandleContent', '')
        // }
        // if (this.$store.state.setTicketType==='图形开票'){
        //   await submitOperateRecord(params_2,false)
        // }

        if (this.$store.state.canHandle){
          wsSend(this.sendMsgData);
          let pointName=''
          if (this.sendMsgData.cmd==='switchChange'){
            const parts = this.currentSelectMenuItemObj.info.operate_point_name.split(',');
            if (this.sendMsgData.state === '1') {
              pointName = parts[0].slice(-1).toUpperCase() === 'H' ? parts[0] : parts[1];
            } else {
              pointName = parts[0].slice(-1).toUpperCase() === 'H' ? parts[1] : parts[0];
            }

          }else{
            pointName = this.currentSelectMenuItemObj.info.operate_point_name;
          }
          let res = await submitOperateRecord(params,false,pointName)
          if (res.data!==1){
            this.$message.error('提交操作记录接口异常，遥控操作中断......')
          }
        }else{
          this.$message.error('校验未通过,请检查控制编号与测点是否一致')
          this.canSubmit=true
        }
      }
      else{
        this.$message.error('提交中，请勿频繁点击')
      }
    },
    operatorPwdSubmit_0(){
      if (this.operatorPwdObj.username){
        const operator = this.userInfoJson.operatorList.find(
            (item) => item.username === this.operatorPwdObj.username
        );
        if (!operator || operator.pwd !== this.operatorPwdObj.pwd) {
          this.$message.error("操作人密码错误！");
          return;
        }
      }else{
        this.$message.error('请选择操作人！')
        return
      }
      this.$message.success('操作人身份验证通过！')
      this.operatorPwdDialogVisible_0=false
      setTimeout(() => {
        this.operatorPwdDialogVisible=true
      },500)

    },
    getPageData(){
      const params = {
        cmd: "getJgFenTuPage",
        data: {
          ftIndex: this.$route.query.ftIndex,
          jgName: this.$route.query.jgName
        }
      };
      if (this.$store.state.ws && this.$store.state.ws.readyState === WebSocket.OPEN) {
        wsSend(params)
      } else {
        EventBus.$on('ws-connected',() => wsSend(params))
      }
    },
    operatorPwdSubmit() {
      this.showMenu=false
      if (this.adminPwdObj.username){

        const admin = this.userInfoJson.adminList.find(
            (item) => item.username === this.adminPwdObj.username
        );
        if (!admin || admin.pwd !== this.adminPwdObj.pwd) {
          this.$message.error("监护人密码错误！");
          return;
        }
      }else{
        this.$message.error('请选择监护人!')
        return
      }
      this.$message.success('验证通过,正在打开遥控界面')
      this.operatorPwdDialogVisible=false

      this.operatorPwdObj={
        username:'',
        pwd:''
      }
      this.adminPwdObj={
        username:'',
        pwd:''
      }
      this.rightMenuObj.currentSelectItem = {
        label:'遥控',
        value:1
      }
      this.currentSelectMenuItemObj = this.rightMenuObj
      this.currentSelectedStatus = ''
      setTimeout(() => {
        this.dialogVisible = true
      },500)

    },
  },
  created() {
  },
  mounted() {
    this.$nextTick(() => {
      setTimeout(() => {
        this.getPageData();
      }, 0);
    });
    EventBus.$on('ws-message',this.messageHandler)
  },
  beforeDestroy() {
    EventBus.$off('ws-message',this.messageHandler)
    EventBus.$off('ws-connected')
  }
}
